package com.xci.platform.web.core;

import com.xci.platform.core.BoolMessage;
import com.xci.platform.helper.WebHelper;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 根据请求类型处理404错误:
 * 如果是普通请求(浏览器),返回错误页面
 * 如果是Ajax请求,返回统一的Json错误
 */
@RestController
public class NotFoundController implements ErrorController {

    private static final String ERROR_PATH = "/error";

    @RequestMapping(value = ERROR_PATH)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public Object handleError(HttpServletRequest request, HttpServletResponse response,Exception e) {
        // int status = response.getStatus();

        boolean isAjax = WebHelper.isAjax(request);
        boolean isApp = WebHelper.isApp(request);
        if (isAjax||isApp) {
            // JsonResult result = new JsonResult();
            // result.setMsg("请求的url无效");
            return new BoolMessage(false, e.getMessage());
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("url", request.getRequestURL());
            modelAndView.setViewName("error/error404");
            return modelAndView;
        }
    }

    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }
}
